package cn.wizzer.app.web.commons.ext.websocket.action;

import cn.wizzer.app.crown.modules.models.CrownLeague;
import cn.wizzer.app.crown.modules.models.CrownMatch;
import cn.wizzer.app.crown.modules.models.CrownViewPoint;
import cn.wizzer.app.crown.modules.models.caches.CrownMatchChampion;
import cn.wizzer.app.crown.modules.models.caches.CrownMatchSimplex;
import cn.wizzer.app.crown.modules.models.enums.MatchStageEnum;
import cn.wizzer.app.crown.modules.models.enums.MatchTypeEnum;
import cn.wizzer.app.crown.modules.models.enums.PlayWayEnum;
import cn.wizzer.app.crown.modules.models.vo.CrownViewPointVO;
import cn.wizzer.app.crown.modules.services.CrownMatchService;
import cn.wizzer.app.crown.modules.services.ViewPointOrderService;
import cn.wizzer.app.crown.modules.services.ViewPointService;
import cn.wizzer.app.crown.modules.services.order.CrownOrderService;
import cn.wizzer.app.sys.modules.models.SysDict;
import cn.wizzer.app.user.modules.models.Gift;
import cn.wizzer.app.user.modules.models.GroupInfo;
import cn.wizzer.app.user.modules.models.LiveBroadcast;
import cn.wizzer.app.user.modules.models.User;
import cn.wizzer.app.user.modules.models.enums.BizTypeEnum;
import cn.wizzer.app.user.modules.models.vo.LiveInfo;
import cn.wizzer.app.user.modules.services.*;
import cn.wizzer.app.user.modules.services.account.UserAccountRecordService;
import cn.wizzer.app.web.commons.core.WebApiMainLauncher;
import cn.wizzer.app.web.commons.ext.websocket.MyWebSocketClient;
import cn.wizzer.app.web.commons.ext.websocket.main.action.BaseNettyAction;
import cn.wizzer.app.web.commons.ext.websocket.main.action.NettyAction;
import cn.wizzer.app.web.commons.utils.NettyMsgUtil;
import cn.wizzer.app.web.commons.utils.RedisUtil;
import cn.wizzer.app.web.modules.controllers.crown.ApiCrownMatchController;
import cn.wizzer.app.web.modules.controllers.crown.viewPoint.ApiViewPointController;
import cn.wizzer.app.web.modules.controllers.sys.ApiDictController;
import cn.wizzer.app.web.modules.controllers.user.ApiLiveBroadcastController;
import cn.wizzer.app.web.modules.controllers.user.ApiUserController;
import cn.wizzer.framework.base.Result;
import cn.wizzer.framework.page.Pagination;
import cn.wizzer.framework.util.JSONUtil;
import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.fastjson.JSONObject;
import io.netty.channel.Channel;
import org.apache.commons.lang3.EnumUtils;
import org.nutz.boot.NbApp;
import org.nutz.dao.Cnd;
import org.nutz.dao.Sqls;
import org.nutz.dao.sql.Sql;
import org.nutz.integration.jedis.RedisService;
import org.nutz.ioc.impl.PropertiesProxy;
import org.nutz.ioc.loader.annotation.Inject;
import org.nutz.ioc.loader.annotation.IocBean;
import org.nutz.lang.Times;
import org.nutz.log.Log;
import org.nutz.log.Logs;

import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;

import static cn.wizzer.app.match.modules.models.constant.Fields.PHONE_NUM;

/**
 * Created by wizzer on 2018/4/4.
 */
@IocBean
@NettyAction(uri = "/api/test")
public class ApiTestAction extends BaseNettyAction {
    private final static Log log = Logs.get();
    public static final String WS_URL = "ws://127.0.0.1:8090/ws";
//    public static final String WS_URL = "ws://47.114.170.23/:8090/ws";
    @Inject
    private PropertiesProxy conf;
    @Inject
    private RedisService redisService;

    @Inject()
    private ApiUserController userController;
    @Inject
    @Reference
    private UserService userService;
    @Inject
    @Reference
    private UserAccountRecordService userAccountRecordService;
    @Inject
    private ApiDictController dictController;
    @Inject
    @Reference
    private LiveBroadcastService liveBroadcastService;
    @Inject
    private ApiLiveBroadcastController liveBroadcastController;
    @Inject
    @Reference
    private GroupInfoService groupInfoService;
    @Inject
    @Reference
    private GroupMemberService groupMemberService;

    public void init() {

        //RpcContext.getContext().set("ip","172.16.41.154");

        RedisUtil.init(redisService);
    }


    @Override
    public Result action(Channel income, JSONObject params) {
        log.info("执行开始");
        //直播类型
        List<SysDict> sysDictList = JSONObject.parseArray(JSONObject.toJSONString(dictController.get("startLiveCategory").getData()), SysDict.class);
        for (int i = 0; i < 10000; i++) {
            int finalI = i;
            new Thread(() -> {
                try {
                    log.info("第" + finalI + "个");
                    StringBuilder nickname = new StringBuilder(String.valueOf(finalI));
                    int length = nickname.length();
                    for (int j = 0; j < 4 - length; j++) {
                        nickname.insert(0, "0");
                    }
                    String phone = "1391234" + nickname;
                    try {
                        String inviteCode = userService.fetch(Cnd.where("phone", "=", finalI < 100 ? PHONE_NUM : "139123400" + phone.substring(9))).getInviteCode();
                        userController.regPhone("code", phone, nickname.toString(), "msgId", "8d969eef6ecad3c29a3a629280e686cf0c3f5d5a86aff3ca12020c923adc6c92", inviteCode);
                    } catch (Exception e) {
                    }
                    User user = userService.fetch(Cnd.where("phone", "=", phone));
                    //设置权限
                    //user.setCollect(true);
                    user.setPlayable(true);
                    if (finalI < 100) {
                        user.setAgent(true);
                    }
                    if (finalI % 2 == 0) {
                        user.setAttendant(true);
                    } else {
                        user.setAnchor(true);
                    }
                    userService.updateUser(user);
                    //充值1000W
                    userAccountRecordService.add(user.getId(), BigDecimal.valueOf(10000000), BizTypeEnum.RECHARGE, user.getId());

                    //若是主播则开启直播
                    if (user.isAnchor()) {
                        log.info(user.getNickName() + "主播开启直播");
                        SysDict sysDict = sysDictList.get(new Random().nextInt(sysDictList.size()));
                        startLive(user, sysDict);
                    }
                    //加入直播间
                    log.info(user.getNickName() + "加入直播间并发言");
                    LiveInfo liveInfo = joinRoom(user, income);
                    //刷礼物
                    log.info(user.getNickName() + "刷礼物");
                    sendGift(user, liveInfo.getUserId(), liveInfo.getId(), income);
                    //发观点
                    log.info(user.getNickName() + "发观点");
                    publishVP(user);
                    //买观点
                    log.info(user.getNickName() + "买观点");
                    buyVP(user);
                    if (user.isAttendant()) {
                        //客服上线
                        log.info(user.getNickName() + "客服上线");
                        MyWebSocketClient myWebSocketClient = attendantLogin(user, income);
                        //客服人员回话
                        log.info(user.getNickName() + "客服人员回话");
                        attendantSend(user, myWebSocketClient, income);
                    } else {
                        //非客服人员找客服唠嗑
                        log.info(user.getNickName() + "非客服人员找客服唠嗑");
                        userSend(user, income);
                    }
                    //群聊
                    {
                        //创建群聊 name: anchor & proxy & all & 0~100（代理创建并加入）
                        //当用户为主播时，加入群聊 anchor, 若群聊不存在则创建群聊 anchor
                        if (user.isAnchor()) {
                            GroupInfo anchorGroup = groupInfoService.fetch(Cnd.where("groupName", "=", "anchor"));
                            if (anchorGroup == null) {
                                log.info(user.getNickName() + "创建群聊 anchor");
                                //创建群聊
                                anchorGroup = new GroupInfo();
                                anchorGroup.setGroupName("anchor");
                                anchorGroup.setMasterId(user.getId());
                                groupInfoService.add(anchorGroup);
                            } else {
                                log.info(user.getNickName() + "加入群聊 anchor");
                                //加入群聊
                                groupMemberService.addMember(user.getId(), anchorGroup.getId());
                            }
                        }
                        //统一加入all
                        //加入群聊 all, 若群聊不存在则创建群聊 all
                        GroupInfo allGroup = groupInfoService.fetch(Cnd.where("groupName", "=", "all"));
                        if (allGroup == null) {
                            //创建群聊
                            log.info(user.getNickName() + "创建群聊 all");
                            allGroup = new GroupInfo();
                            allGroup.setGroupName("all");
                            allGroup.setMasterId(user.getId());
                            groupInfoService.add(allGroup);
                        } else {
                            log.info(user.getNickName() + "加入群聊 all");
                            //加入群聊
                            groupMemberService.addMember(user.getId(), allGroup.getId());
                        }
                        //当用户为代理时加入代理群
                        if (user.isAgent()) {
                            GroupInfo proxyGroup = groupInfoService.fetch(Cnd.where("groupName", "=", "proxy"));
                            if (proxyGroup == null) {
                                log.info(user.getNickName() + "创建群聊 proxy");
                                //创建群聊
                                proxyGroup = new GroupInfo();
                                proxyGroup.setGroupName("proxy");
                                proxyGroup.setMasterId(user.getId());
                                groupInfoService.add(proxyGroup);
                            } else {
                                log.info(user.getNickName() + "加入群聊 proxy");
                                //加入群聊
                                groupMemberService.addMember(user.getId(), proxyGroup.getId());
                            }
                            //同一代理下的用户加入同一（0~100群聊）群聊
                            //创建代理用户群，收代理下的用户
                            //创建群聊
                            log.info(user.getNickName() + "创建代理群聊");
                            GroupInfo agentGroup = new GroupInfo();
                            agentGroup.setGroupName(user.getUserName() + user.getPhone());
                            agentGroup.setMasterId(user.getId());
                            groupInfoService.add(agentGroup);
                        } else {
                            log.info(user.getNickName() + "加入代理群聊");
                            //不为代理时查询代理，加入代理用户群
                            User fetch = userService.fetch(user.getInviter());
                            GroupInfo groupInfo = groupInfoService.fetch(Cnd.where("groupName", "=", fetch.getUserName() + fetch.getPhone())
                                    .and("masterId", "=", fetch.getId()));
                            if (groupInfo != null) {
                                groupMemberService.addMember(user.getId(), groupInfo.getId());
                            }
                        }
                        new Thread(() -> {
                            try {
                                MyWebSocketClient client = new MyWebSocketClient(WS_URL);
                                client.syncConnect();
                                int h = new Random().nextInt(3) + 1;
                                long now = System.currentTimeMillis();
                                long end = now + (h * 60 * 60 * 1000);
                                boolean flag = true;
                                //for 1~3h 1s一次发送
                                Sql sql = Sqls.create("SELECT i.* " +
                                        "FROM group_member m " +
                                        "LEFT JOIN group_info i ON m.groupId = i.id " +
                                        "WHERE m.delFlag = 0 AND m.userId = @userId");
                                int num = 1;
                                while (flag) {
                                    if (System.currentTimeMillis() >= end) {
                                        flag = false;
                                    }
                                    //获取群聊列表并逐个发送消息
                                    sql.setParam("userId", user.getId());
                                    List<GroupInfo> list = groupInfoService.listEntity(sql);
                                    String content = "我叫：" + user.getNickName() +
                                            "现在是" + Times.format("yyyy-MM-dd HH:mm:ss", Times.now()) + "，这是我第" + num + "次发消息";
                                    for (GroupInfo groupInfo : list) {
                                        client.send("/group/send?appid=" + user.getId() +
                                                "&token=1&equipment=MOBILE&type=TEXT&content=" + content +
                                                "&groupId=" + groupInfo.getId());
                                    }
                                    num++;
                                    // sleep1~10秒
                                    Thread.sleep((new Random().nextInt(10) + 1) * 1000);
                                }
                                log.info(user.getNickName() + user.getNickName() + "的群聊通道关闭");
                                client.close();
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        }).start();
                    }
                    //注单
                    {
                        //单式
                        log.info(user.getNickName() + "创建单式订单");
                        addSimplex(user);
                        //冠军
                        log.info(user.getNickName() + "创建冠军订单");
                        addChampion(user);
                        //综合
                        log.info(user.getNickName() + "创建综合订单");
                        addComplex(user);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }).run();
        }
        log.info("执行结束");
        return Result.success();
    }

    private MyWebSocketClient attendantLogin(User user, Channel income) {
        try {
            MyWebSocketClient client = new MyWebSocketClient(WS_URL);
            client.syncConnect();
            //客服上线查看最近会话列表
            client.send("/attendant/target/users?appid=" + user.getId() + "&token=1&equipment=PC");
            new Thread(()->{
                //websocket建立连接
                try {
                    Thread.sleep((new Random().nextInt(3) + 1) * 60 * 60 * 1000);
                    //离线
                    client.send("/attendant/logout?appid=" + user.getId() + "&token=1&equipment=PC");
                    log.info(user.getNickName() + "客服离线，通道关闭");
                    client.close();
                }catch (Exception e){
                    e.printStackTrace();
                }
            }).start();
            return client;
        }catch (Exception e){
            e.printStackTrace();
        }
        return null;
    }

    private void buyVP(User user) {
        new Thread(()->{
            Pagination pagination = viewPointService.listPage(1, new Random(500).nextInt(2000), "", user.getId(), null, null);
            List<CrownViewPointVO> list =  pagination.getList();
            for (CrownViewPointVO vo : list) {
                try {
                    viewPointOrderService.add(user.getId(),vo.getId());
                }catch (Exception e){

                }
            }
        }).start();
    }
    @Inject
    @Reference
    private ViewPointService viewPointService;
    @Inject
    @Reference
    private ViewPointOrderService viewPointOrderService;
    @Inject
    private ApiViewPointController viewPointController;
    @Inject
    private ApiCrownMatchController matchController;
    private void publishVP(User user) {
        ArrayList<BigDecimal> prices = Result.createList(BigDecimal.valueOf(0), BigDecimal.valueOf(28), BigDecimal.valueOf(128));
        for (MatchTypeEnum matchTypeEnum : EnumUtils.getEnumList(MatchTypeEnum.class)) {
            Pagination data = (Pagination) viewPointController.match(1, 100, matchTypeEnum).getData();
            List<CrownMatch> matchList = data.getList();
            for (CrownMatch match : matchList) {
                new Thread(()->{
                    try{
                            CrownMatch crownMatch = (CrownMatch) matchController.allPlayWay(match.getId(), PlayWayEnum.R).getData();
                        CrownMatchSimplex crownMatchSimplex;
                        try (Stream<CrownMatchSimplex> crownMatchSimplexStream = crownMatch.getMatchSimplexList().stream()
                                .filter(simplex -> simplex.getNo2() < 5)) {
                            crownMatchSimplex = crownMatchSimplexStream
                                    .min(Comparator.comparing(CrownMatchSimplex::getOdds))
                                    .get();
                        }
                        CrownViewPoint crownViewPoint = new CrownViewPoint();
                        crownViewPoint.setContent(user.getNickName()+"\n0123456789\n0123456789\n0123456789\n0123456789\n"+user.getPhone());
                        crownViewPoint.setOdds(crownMatchSimplex.getOdds());
                        crownViewPoint.setMatchId(crownMatch.getId());
                        crownViewPoint.setMatchType(crownMatch.getType());
                        crownViewPoint.setPrice(prices.get(new Random().nextInt(prices.size())));
                        crownViewPoint.setRefundable(new Random().nextBoolean());
                        crownViewPoint.setTitle(user.getNickName()+":"+crownMatch.getMbTeam()+"VS"+crownMatch.getTgTeam());
                        crownViewPoint.setSelectedOption(JSONUtil.toJSONString(crownMatchSimplex));
                        crownViewPoint.setShowBets(JSONUtil.toJSONArrayString(crownMatch.getMatchSimplexList().stream()
                                .filter(simplex -> simplex.getNo2() < 5).collect(Collectors.toList())));
                        viewPointService.add(crownViewPoint,user.getId());

                    }catch (NoSuchElementException ignored){
                    }catch (Exception e){
                        e.printStackTrace();
                    }
                }).start();
            }
        }
    }

    private void userSend(User user, Channel income) {
        try {
            new Thread(()->{
                try {
                    MyWebSocketClient client = new MyWebSocketClient(WS_URL);
                    client.syncConnect();
                    long now = System.currentTimeMillis();
                    long end = now + (60 * 60 * 1000);
                    boolean flag = true;
                    //openAction
                    client.send("/attendant/open?appid=" + user.getId() + "&token=1&equipment=MOBILE");
                    int i = 1;
                    while (flag){
                        //for 1h
                        if(System.currentTimeMillis() >= end){
                            flag = false;
                        }
                        //sendAction
                        String content = "我是" + user.getNickName() + "：这是第" + i + "条";
                        client.send("/user/send?appid=" + user.getId() + "&token=1&equipment=MOBILE&type=TEXT&content=" + content);
                        try {
                            //sleep 1-10s
                            Thread.sleep((new Random().nextInt(10) + 1) * 1000);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                        i++;
                    }
                    log.info(user.getNickName() + "用户发言结束，通道关闭");
                    client.close();
                }catch (Exception e){
                    e.printStackTrace();
                }
            }).start();
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    private void attendantSend(User user, MyWebSocketClient client, Channel income) {
        try {
            new Thread(()->{
                try {
                    long now = System.currentTimeMillis();
                    long end = now + (60 * 60 * 1000);
                    boolean flag = true;
                    while (flag) {
                        //for 1h
                        if (System.currentTimeMillis() >= end) {
                            flag = false;
                        }
                        //获取用户列表 回话
                        client.send("/attendant/attendant/sendAll?appid=" + user.getId() + "&token=1&equipment=PC");
                        try {
                            //sleep 1-10s
                            Thread.sleep((new Random().nextInt(10) + 1) * 1000);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                    log.info(user.getNickName() + "客服回复结束，通道关闭");
                    client.close();
                }catch (Exception e){
                    e.printStackTrace();
                }
            }).start();
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    private void sendMsg(User user) {
        try {
            MyWebSocketClient client = new MyWebSocketClient(WS_URL);
            //建立连接
            client.syncConnect();
            new Thread( () -> {
                //for i 10*100
                for (int i = 0; i < 10; i++) {
                    for (int j = 0; j < 100; j++) {
                        //sendMsgAction
                        client.send("/send?content=(+" + i + "+)大家好我是" + user.getNickName() + "(" + j + ")");
                        try {
                            //sleep(1000~10*1000)
                            Thread.sleep((new Random().nextInt(10) + 1) * 100  * 1000);
                        } catch (InterruptedException e) {}
                    }
                }
//                log.info();(user.getNickName() + "发言结束，通道关闭");
                client.close();
            }).start();
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    private LiveInfo joinRoom(User user, Channel income) {
        List<LiveInfo> lives = (List) liveBroadcastService.getLiveList("[]").getData();
        LiveInfo liveInfo = lives.get(new Random().nextInt(lives.size()));
        try {
            MyWebSocketClient client = new MyWebSocketClient(WS_URL);
            //建立连接
            client.syncConnect();
            //加入房间
            client.send("/joinRoom?roomId=" + liveInfo.getId());
            //登录
            client.send("/login?appid=" + user.getId() + "&token=1&equipment=MOBILE");
            //随机加入一个房间（websocket接入）
            if(liveInfo != null){
                new Thread( ()->{
                    try {
                        log.info(user.getNickName() + "开始发言");
                        //发言总花费时间
                        long useTime = 0;
                        for (int i = 0; i < 10; i++) {
                            for (int j = 0; j < 100; j++) {
                                //sendMsgAction
                                client.send("/send?content=(" + i + ")大家好我是" + user.getNickName() + "(" + j + ")");
                                long needTime = (new Random().nextInt(10) + 1) * 1000;
                                //sleep(1000~10*1000)
                                Thread.sleep(needTime);
                                useTime = useTime + needTime;
                            }
                        }
                        //sleep(1-10h)
                        log.info(user.getNickName() + "发言结束，聊天室挂机");
                        //聊天室滞留总需要时间
                        long needTime = (new Random().nextInt(10) + 1) * 60 * 60 * 1000;
                        long remainTime = needTime - useTime;
                        if (remainTime > 0){
                            Thread.sleep(remainTime);
                        }
                        //liveRoom
                        client.send("/leave?roomId=" + liveInfo.getId());
                        log.info(user.getNickName() + "离开聊天室，通道关闭");
                        client.close();
                    }catch (Exception e){
                        e.printStackTrace();
                    }
                }).start();
            }
            return liveInfo;
        }catch (Exception e){
            e.printStackTrace();
            return null;
        }
    }

    private void startLive(User user, SysDict sysDict) {
        //开播接口
        String categoryId = sysDict.getId();
        String userId = user.getId();
        liveBroadcastService.end(userId);
        Result start = liveBroadcastService.start(null, null, user.getId(), "测试" + user.getNickName(),
                user.getNickName() + "在测试", null, categoryId);
        String liveNo;
        if(start.getCode() == 1){
            LiveBroadcast liveBroadcast = (LiveBroadcast) start.getData();
            liveNo = liveBroadcast.getUserId() + "-" +
                    (liveBroadcast.getVideoId() != null ? liveBroadcast.getVideoId() : liveBroadcast.getCategoryId());
        }else {
            liveNo =  userId + "-" + categoryId;
        }
        //开播回调接口
//        LiveInfo liveInfo = JSONUtil.parseStringToJavaBean(LiveInfo.class, redisService.hget(KEY_LIVE, liveNo));
        LiveInfo liveInfo = liveBroadcastService.hget(liveNo);
        if (liveInfo.getUserId().equals(user.getId())) {
            liveBroadcastService.unRemoveLive(liveNo);
        }
    }
    @Inject
    @Reference
    private GiftOrderService orderService;
    @Inject
    @Reference
    private GiftService giftService;
    private void sendGift(User user, String toUser, String liveNo, Channel income) {
        new Thread( () -> {
            log.info(user.getNickName() + "开始刷礼物");
            List<Gift> query = giftService.query();
            for (int i = 0; i < query.size() * 100; i++) {
                log.info(user.getNickName() + "待刷数量：" + (query.size() * 100 - i));
                Gift gift = query.get(i % query.size());
                String giftId = gift.getId();
                String appid = user.getId();
                try {
                    orderService.create(giftId, 1, appid, toUser, liveNo);
                    NettyMsgUtil.sendGiftMessage(liveNo, appid, giftId, 1, gift.getName(), gift.getCoverPic());
                    Thread.sleep(1000);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            log.info(user.getNickName() + "刷礼物结束");
        }).start();
    }

    @Inject
    @Reference
    private CrownMatchService crownMatchService;

    @Inject
    @Reference
    private CrownOrderService crownOrderService;

    private void addSimplex(User user) {
        //注单金额
        BigDecimal amount = BigDecimal.valueOf(100);
        //赛事列表
        for (MatchStageEnum matchStageEnum : EnumUtils.getEnumList(MatchStageEnum.class)) {
            for (MatchTypeEnum matchTypeEnum : EnumUtils.getEnumList(MatchTypeEnum.class)) {
                Pagination matchData = null;
                try {
                    matchData = crownMatchService.matchList(matchStageEnum, matchTypeEnum.name(),"", 1, 100);
                }catch (Exception e){}
                List<CrownMatch> list = matchData.getList();
                for (CrownMatch crownMatch : list) {
//                    Result allPlayWayResult = crownMatchController.allPlayWay(crownMatch.getId(), PlayWayEnum.R);
//                    CrownMatch matchDetail = (CrownMatch)allPlayWayResult.getData();
//                    List<CrownMatchSimplex> matchSimplexList = matchDetail.getMatchSimplexList();
                    List<CrownMatchSimplex> matchSimplexList = crownMatch.getMatchSimplexList();
                    for (CrownMatchSimplex crownMatchSimplex : matchSimplexList) {
                        new Thread(()->{
                            try{
                                //注单
                                crownOrderService.createSimplex(user.getId(),amount,crownMatchSimplex);
                            }catch (Exception e){}
                        }).start();
                    }
                }
            }
        }
        //循环注单
    }

    private void addChampion(User user) {
        //注单金额
        BigDecimal amount = BigDecimal.valueOf(100);
        //联赛列表
        for (MatchTypeEnum matchTypeEnum : EnumUtils.getEnumList(MatchTypeEnum.class)) {
            Pagination leagueData = null;
            try {
                leagueData = crownMatchService.p3MatchList(matchTypeEnum.name(), "",1, 100);
            }catch (Exception e){}
            List<CrownLeague> leagueList = leagueData.getList();
            for (CrownLeague crownLeague : leagueList) {
                for (CrownMatchChampion crownMatchChampion : crownLeague.getMatchChampionList()) {
                    new Thread(()->{
                        try {
                            crownOrderService.createChampion(user.getId(),amount,crownMatchChampion);
                        }catch (Exception e){};
                    }).start();
                }
            }
        }
        // 循环注单
    }

    private void addComplex(User user) {
        BigDecimal amount = BigDecimal.valueOf(100);
        for (MatchTypeEnum matchTypeEnum : EnumUtils.getEnumList(MatchTypeEnum.class)) {
            Pagination p3Data = null;
            try{
                p3Data = crownMatchService.p3MatchList(matchTypeEnum.name(), "", 1, 100);
            }catch (Exception e){}
            List<CrownMatch> p3List = p3Data.getList();
            //随机选取3~10个赛事中赔率最低的玩法
            for (int i = 0; i < p3List.size(); i++) {
                new Thread(()->{
                    int matchLength = new Random(3).nextInt(11);
                    Set<String> matchSet = new HashSet<>();
                    boolean flag = true;
                    //随机选择matchLength个赛事
                    while (flag){
                        matchSet.add(p3List.get(new Random(0).nextInt(p3List.size())).getId());
                        if (matchLength<=Math.min(matchSet.size(),p3List.size())) {
                            flag = false;
                        }
                    }
                    //抽取其中最低赔率的玩法
                    List<CrownMatchSimplex> p3Simplexs = p3List.stream()
                            .filter(match -> matchSet.contains(match.getId()))
                            .map(match -> {
                                Optional<CrownMatchSimplex> min = match.getMatchSimplexList().stream().min(Comparator.comparing(CrownMatchSimplex::getOdds));
                                return min.get();
                            }).collect(Collectors.toList());

                    try{
                        crownOrderService.createComplex(user.getId(),amount,p3Simplexs);
                    }catch (Exception e){}
                }).start();
            }
        }
    }

    // 测试类可提供public的static的createNbApp方法,用于定制当前测试类所需要的NbApp对象.
    // 测试类带@IocBean或不带@IocBean,本规则一样生效
    // 若不提供,默认使用当前测试类作为MainLauncher.
    // 也可以自定义NbJUnit4Runner, 继承NbJUnit4Runner并覆盖其createNbApp方法
    public static NbApp createNbApp() {
        NbApp nb = new NbApp().setMainClass(WebApiMainLauncher.class).setPrintProcDoc(false);
        nb.getAppContext().setMainPackage("cn.wizzer");
        return nb;
    }
}
